import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link, useLocation } from 'react-router-dom';
import './App.css';
import routes from './routes';

function AppContent() {
  const location = useLocation();
  
  // 监听主应用传来的路由变化事件
  React.useEffect(() => {
    const handleRouteChange = (event) => {
      console.log('[react-app] received route change from main app:', event.detail);
    };
    
    window.addEventListener('main-app-route-change', handleRouteChange);
    return () => {
      window.removeEventListener('main-app-route-change', handleRouteChange);
    };
  }, []);
  
  return (
    <div className="app">
      <header className="app-header">
        <h1>React 子应用</h1>
        <p>当前路由: {location.pathname}</p>
      </header>
      
      <nav className="app-nav">
        <Link to="/">首页</Link>
        <Link to="/page1">Page 1</Link>
        <Link to="/page2">Page 2</Link>
        <Link to="/page3">Page 3</Link>
      </nav>
      
      <div className="app-content">
        <Routes>
          {routes.map((route, index) => (
            <Route key={index} path={route.path} element={route.element} />
          ))}
        </Routes>
      </div>
    </div>
  );
}

function App() {
  return (
    <Router basename={window.__POWERED_BY_QIANKUN__ ? '/react' : '/'}>
      <AppContent />
    </Router>
  );
}

export default App;